package com.itcast.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 需求：account 表中 添加一条记录
 */
public class jdbcDemo2 {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;

        try {
            // 1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2.定义 sql
            String sql = "INSERT INTO account VALUES (NULL,'王武',3000)";
            // 3.获取 Connection 对象
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root");
            // 4.获取执行 sql 的对象 Statement
            statement = connection.createStatement();
            // 5.执行 sql
            int count = statement.executeUpdate(sql); // 影响的行数
            // 6.处理结果
            System.out.println(count);
            if (count > 0) {
                System.out.println("添加成功！");
            } else {
                System.out.println("添加失败！");
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
